package com.wanjia.seal.manager.controller;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.wanjia.seal.manager.controller.ex.*;
import com.wanjia.seal.manager.utils.JsonResult;
import com.wanjia.seal.manager.controller.ex.*;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/*控制层类的基类*/
@ControllerAdvice
public class BaseController {
    /*操作成功的状态码*/
    public static final int OK = 200;

    @ExceptionHandler(value ={ControllerException.class, JWTVerificationException.class} )//用于统一处理抛出的异常
    @ResponseBody
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<>(e);

        if (e instanceof DataNotFoundException){
            result.setState(4000);
            result.setMessage("数据异常");
        }else if (e instanceof OperatorIdNotFoundException){
            result.setState(4001);
            result.setMessage("操作员ID不存在的异常");
        }else if (e instanceof PasswordNotMatchException){
            result.setState(4002);
            result.setMessage("密码不匹配的异常");
        }else if(e instanceof OperatorIdDuplicateException){
            result.setState(4003);
            result.setMessage("用户名被占用的异常");
        }else if (e instanceof TokenExpiredException){
            result.setState(401);
            result.setMessage("token失效");
        }else if (e instanceof userexistException){
            result.setState(4004);
            result.setMessage("存在子项数据，不能删除");
        }else if (e instanceof BankexistException){
            result.setState(4005);
            result.setMessage("信息重复，不能增加");
        }else if (e instanceof yanzhenException){
            result.setState(4006);
            result.setMessage("验证不通过");
        }else if (e instanceof yanzhennotfoundException){
            result.setState(4007);
            result.setMessage("表格中机构或用户不存在");
        }else if (e instanceof SealcardNotFoundException){
            result.setState(4008);
            result.setMessage("印鉴卡号不存在");
        }
        return result;
    }

    protected final Integer getTokenFromSession(HttpSession session){
        return Integer.valueOf( session.getAttribute("token").toString());
    }

    protected final String getOperatoridFromSession(HttpSession session){
        return session.getAttribute("OperatorID").toString();
    }
}